#ifndef CALREQUEST_HPP
#define CALREQUEST_HPP

#include "protocol.hpp"

#include <iostream>

enum
{
    SUCESS = 0,
    DIVERR = 2,
    MODERR,
    NONE
};

class Calculator // 上层业务
{
public:
    Calculator() {};

    Response CalculatorHandler(const Request &req)
    {
        // 提前声明Response变量，这样可以确保每个case都是同一作用域中的变量
        Response resp(-1, NONE);
        int num1 = req.GetNum1();
        int num2 = req.GetNum2();

        switch (req.GetOp())
        {
        case '+':
            resp = Response(num1 + num2, SUCESS);
            break;
        case '-':
            resp = Response(num1 - num2, SUCESS);
            break;
        case '*':
            resp = Response(num1 * num2, SUCESS);
            break;
        case '/':
            if (num2 == 0)
            {
                resp = Response(-1, DIVERR);
            }  
            else
            {
                resp = Response(num1 / num2, SUCESS);
            }
            break;
        case '%':
            if (num2 == 0)
            {
                resp = Response(-1, MODERR);
            }
            else
            {
                resp = Response(num1 % num2, SUCESS);
            }
            break;
        default:
            resp = Response(-1, NONE);
            break;
        }

        return resp;
    }

    std::string Handler(std::string &package)
    {
        std::string text;
        if (!Decode(package, &text))
            return "";

        Request req;
        if (!req.Deserialize(text))
            return "";

        text = "";
        Response resp = CalculatorHandler(req);
        resp.Serialize(&text);
        text = Encode(text);
        // lg(DEBUG, "Calculator() debug : %s", text.c_str());
        return text;
    }

    ~Calculator() {};
};
#endif